import logger from '../core/logger';
import apiInfo from './core/apiInfo';
import { clientBase } from './core/clientBase';
import returnModel from '../model/common/returnModel';
import articleModel from '../model/articles/articleModel';
import articleCategories from '../model/articles/articleCategories';

class articleClient extends clientBase {
  getCategories(): Promise<returnModel<Array<articleCategories>>> {
    var self = this;
    return new Promise((resolve) => {
      let info = new apiInfo('https://api.bilibili.com/x/article/categories');
      info.needKey = false;
      this.client.getResult(info).then((res) => {
        try {
          if (res.code == 0) {
            let data: Array<articleCategories> = [];
            for (let item of res.data) {
              let row = new articleCategories(item);
              data.push(row);
            }
            resolve(self.buildSuccessResult<Array<articleCategories>>(data));
          } else
            resolve(self.buildFailedResult<Array<articleCategories>>(res.toString()));
        } catch (e) {
          logger.error(e);
          resolve(self.buildExceptionResult<Array<articleCategories>>(e));
        }
      });
    });
  }

  getHome(pageIndex: number): Promise<returnModel<articleModel>> {
    var self = this;
    return new Promise((resolve) => {
      let info = new apiInfo("https://api.bilibili.com/x/article/home", `&cid=0&pn=${pageIndex}&ps=20`);
      info.needKey = false;
      this.client.getResult(info).then((res) => {
        try {
          if (res.code == 0)
            resolve(self.buildSuccessResult<articleModel>(res.data));
          else
            resolve(self.buildFailedResult<articleModel>(res.toString()));
        } catch (e) {
          logger.error(e);
          resolve(self.buildExceptionResult<articleModel>(e));
        }
      });
    });
  }

  getRecommends(cid: number, pageIndex: number): Promise<returnModel<Array<articleModel>>> {
    var self = this;
    return new Promise((resolve) => {
      let info = new apiInfo("https://api.bilibili.com/x/article/recommends", `&cid=${cid}&from=2&pn=$${pageIndex}&ps=20&sort=0`);
      info.needKey = true;
      this.client.getResult(info).then((res) => {
        try {
          if (res.code == 0) {
            var data: Array<articleModel> = res.data;
            resolve(self.buildSuccessResult<Array<articleModel>>(data));
          } else
            resolve(self.buildFailedResult<Array<articleModel>>(res.toString()));
        } catch (e) {
          logger.error(e);
          resolve(self.buildExceptionResult<Array<articleModel>>(e));
        }
      });
    });
  }
}
export default new articleClient();